package com.kantboot.system.user.dao.repository.entity;

import com.kantboot.system.user.domain.entity.SysUserBalance;
import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.math.BigDecimal;
import java.util.List;

public interface SysUserBalanceRepository extends JpaRepository<SysUserBalance,Long>
{

    @Transactional
    @Modifying
    @Query("""
        UPDATE SysUserBalance
        SET number = number + :number
        WHERE userId = :userId
        AND balanceCode = :balanceCode
    """)
    void addBalance(
            @Param("balanceCode") String balanceCode,
            @Param("userId") Long userId,
            @Param("number") BigDecimal number);

    /**
     * 根据用户id和余额code查询余额
     * @param userId 用户id
     * @param balanceCode 余额code
     * @return 余额
     */
    @Query("""
        SELECT number
        FROM SysUserBalance
        WHERE userId = :userId
        AND balanceCode = :balanceCode
    """)
    Long findNumberByUserIdAndBalanceCode(Long userId, String balanceCode);

    /**
     * 修改状态
     */
    @Transactional
    @Modifying
    @Query("""
        UPDATE SysUserBalance
        SET statusCode = :statusCode
        WHERE userId = :userId
        AND balanceCode = :balanceCode
    """)
    void updateStatusCodeByUserIdAndBalanceCode(
            @Param("userId") Long userId,
            @Param("balanceCode") String balanceCode,
            @Param("statusCode") String statusCode);

    /**
     * 根据用户id和余额code查询余额
     * @param userId 用户id
     * @param balanceCode 余额code
     * @return 余额
     */
    SysUserBalance findByUserIdAndBalanceCode(Long userId, String balanceCode);

    /**
     * 根据用户id和余额code查询余额状态
     * @param userId 用户id
     * @param balanceCode 余额code
     * @return 余额
     */
    @Query("""
        SELECT statusCode
        FROM SysUserBalance
        WHERE userId = :userId
        AND balanceCode = :balanceCode
    """)
    String findStatusCodeByUserIdAndBalanceCode(Long userId, String balanceCode);

    /**
     * 根据用户id查询余额
     */
    List<SysUserBalance> findByUserId(Long userId);

    /**
     * 根据余额编码查询
     */
    List<SysUserBalance> findByBalanceCode(String balanceCode);


}
